package com.joysuch.wwyt.mh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.service.BaseImageRepositoryService;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.mh.bean.vo.CustomizeMonitorTypeVO;
import com.joysuch.wwyt.mh.dto.CustomizeMonitorTypeSelectDto;
import com.joysuch.wwyt.mh.dto.CustomizeMonitorTypeUseCountDto;
import com.joysuch.wwyt.mh.entity.CustomizeMonitorType;
import com.joysuch.wwyt.mh.enums.MonitorTypeEnum;
import com.joysuch.wwyt.mh.mapper.CustomizeMonitorTypeMapper;
import com.joysuch.wwyt.mh.service.CustomizeMonitorPointService;
import com.joysuch.wwyt.mh.service.CustomizeMonitorTypeService;
import com.joysuch.wwyt.workflow.entity.WorkFlowScreenConfig;
import com.joysuch.wwyt.workflow.entity.WorkFlowScreenType;
import com.joysuch.wwyt.workflow.repository.WorkFlowScreenConfigDao;
import com.joysuch.wwyt.workflow.repository.WorkFlowScreenTypeDao;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jingwk
 * @since 2021-07-05
 */
@Service
public class CustomizeMonitorTypeServiceImpl extends ServiceImpl<CustomizeMonitorTypeMapper, CustomizeMonitorType> implements CustomizeMonitorTypeService {

    @Autowired
    private CustomizeMonitorPointService customizeMonitoringPointService;
    @Autowired
    private BaseImageRepositoryService baseImageRepositoryService;
    @Autowired
    private CustomizeMonitorTypeMapper customizeMonitorTypeMapper;
    @Autowired
    private WorkFlowScreenConfigDao workFlowScreenConfigDao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private WorkFlowScreenTypeDao screenTypeDao;

    @Override
    public IPage<CustomizeMonitorType> findListPaging(int pageNo, int size) {
        Page<CustomizeMonitorType> page = new Page<>(pageNo + 1, size);
        LambdaQueryWrapper<CustomizeMonitorType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomizeMonitorType::getDeleteFlag, "0");
        wrapper.eq(CustomizeMonitorType::getTenentId, Context.getCurrentTenantId());
        wrapper.likeRight(CustomizeMonitorType::getOrgCode, Context.getCompanyCode());
        wrapper.orderByDesc(CustomizeMonitorType::getId);
        return super.page(page, wrapper);
    }

    @Override
    public IPage<CustomizeMonitorTypeVO> findTypeInfoListPaging(int pageNo, int size) {
        IPage<CustomizeMonitorType> monitoringTypeIPage = findListPaging(pageNo, size);
        List<CustomizeMonitorType> types = monitoringTypeIPage.getRecords();
        List<CustomizeMonitorTypeVO> typeVOList = new ArrayList<>();
        Map<Long, Long> countMap = getTypeUsingCountMap();
        types.forEach(each -> {
            CustomizeMonitorTypeVO typeVO = new CustomizeMonitorTypeVO();
            BeanUtils.copyProperties(each, typeVO);
            if (MapUtils.isNotEmpty(countMap)) {
                typeVO.setUsingCount(countMap.get(typeVO.getId()));
            }
            String imageUrl = baseImageRepositoryService.generateImageUrlById(typeVO.getImageId());
            typeVO.setImageUrl(imageUrl);
            typeVOList.add(typeVO);
        });
        Page<CustomizeMonitorTypeVO> typeVOPage = new Page<>();
        typeVOPage.setRecords(typeVOList);
        typeVOPage.setTotal(monitoringTypeIPage.getTotal());
        return typeVOPage;
    }

    private Map<Long, Long> getTypeUsingCountMap() {
        List<CustomizeMonitorTypeUseCountDto> useCount = customizeMonitoringPointService.countPointByType();
        return useCount.stream().collect(Collectors.toMap(CustomizeMonitorTypeUseCountDto::getCustomizeMonitoringTypeId, CustomizeMonitorTypeUseCountDto::getUseCount));
    }

    @Override
    public List<CustomizeMonitorTypeSelectDto> allType() {
        return customizeMonitorTypeMapper.allType(Context.getCompanyCode(), Context.getCurrentTenantId());
    }

    @Override
    public boolean saveMonitorType(CustomizeMonitorType customizeMonitoringType) throws ApiBusinessException {
        if (customizeMonitoringType.getId() == null) {
            customizeMonitoringType.setCode(bizCodeGeneratorFacade.jiancedianleixing());
        }
        saveScreenConfig(customizeMonitoringType,"mh");
        return super.saveOrUpdate(customizeMonitoringType);
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean deleteById(Long typeId) {
        CustomizeMonitorType typeInfo = super.getById(typeId);
        workFlowScreenConfigDao.deleteByBizTypeCodeAndEnvironmentPointFlag(typeInfo.getCode(),MonitorTypeEnum.CUSTOM.getValue());
        typeInfo.setDeleteFlag("1");
        return super.updateById(typeInfo);
    }

    /**
     * 保存自定义监测点大屏配置
     *
     * @param monitorType
     */
    private void saveScreenConfig(CustomizeMonitorType monitorType,String screenType) throws ApiBusinessException {
        if (monitorType != null) {
            WorkFlowScreenConfig screenConfig = workFlowScreenConfigDao.findByBizTypeCodeAndEnvironmentPointFlag(monitorType.getCode(), MonitorTypeEnum.CUSTOM.getValue());
            if (screenConfig == null) {
                screenConfig = new WorkFlowScreenConfig();
                screenConfig.setShow(1);
                screenConfig.setShowOrder(1000);
                screenConfig.setValueShow(1);
                screenConfig.setValueShowButton(1);
                screenConfig.setEnvironmentPointFlag(MonitorTypeEnum.CUSTOM.getValue());
                //重大危险源大屏专栏id
                WorkFlowScreenType screenTypeInfo = screenTypeDao.findByCode(screenType);
                if (screenType != null) {
                    screenConfig.setTypeId(screenTypeInfo.getId());
                } else {
                    throw new ApiBusinessException(Status.CODE_STRATEGY_NOT_FOUND);
                }
            }
            screenConfig.setBizTypeCode(monitorType.getCode());
            screenConfig.setBizTypeName(monitorType.getName());
            workFlowScreenConfigDao.save(screenConfig);
        }
    }

}
